﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;
using System.Web;
using System.Web.Profile;
using System.Web.Security;

using SCS.Web.UI.WebControls.Dialogs.Test.Membership;

namespace SCS.Web.UI.WebControls.Dialogs.Test
{
    [ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class AjaxService
    {
        // To use HTTP GET, add [WebGet] attribute. (Default ResponseFormat is WebMessageFormat.Json)
        // To create an operation that returns XML,
        //     add [WebGet(ResponseFormat=WebMessageFormat.Xml)],
        //     and include the following line in the operation body:
        //         WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
        [WebInvoke]
        [OperationContract]
        public string GetDialogContent(string contextKey)
        {
            return "<div>This content was served from a WCF service.</div>";
        }

        [WebInvoke]
        [OperationContract]
        public string GetMembershipContent(string contextKey)
        {
            string[] data = contextKey.Split('#', ',', '|', '$');

            switch (data[0].ToUpper())
            {
                case "FORGOTPASSWORD":
                    return HtmlBuilder.RenderUserControl("~/membership/forgotPassword.ascx", contextKey);
                    
                case "REGISTER":
                    return HtmlBuilder.RenderUserControl("~/membership/register.ascx", contextKey);
                    
                default:
                    return HtmlBuilder.RenderUserControl("~/membership/login.ascx", contextKey);
            }            
        }

        [WebInvoke]
        [OperationContract]
        public ServiceResponse CreateUser(string username, string password, string emailAddress, string securityQuestion, string securityAnswer)
        {
            MembershipCreateStatus status;
            var response = new ServiceResponse { Success = false };

            try
            {
                System.Web.Security.Membership.CreateUser(username, password, emailAddress, securityQuestion, securityAnswer, true, out status);

                switch (status)
                {
                    case MembershipCreateStatus.Success:
                        response.Message = "Your login was created successfully.";
                        response.Success = true;
                        break;

                    case MembershipCreateStatus.DuplicateEmail:
                        response.Message = "Your email address is already in use. Please choose another.";
                        break;

                    case MembershipCreateStatus.DuplicateUserName:
                        response.Message = "Your username is already in use. Please choose another.";
                        break;

                    case MembershipCreateStatus.InvalidEmail:
                        response.Message = "Your email address is invalid. Please try again.";
                        break;

                    case MembershipCreateStatus.InvalidPassword:
                        response.Message = "Your password is not strong enough. Please try again.";
                        break;

                    default:
                        response.Message = "We are unable to create your login. Please try back at another time.";
                        break;
                }
            }
            catch (MembershipCreateUserException ex)
            {
                response.Message = ex.Message;
            }
            catch (MembershipPasswordException ex)
            {
                response.Message = ex.Message;
            }
            catch (Exception)
            {
                response.Message = "We were unable to create your login. Please try back at another time.";
            }

            return response;
        }

        [WebInvoke]
        [OperationContract]
        public ServiceResponse SaveProfile(string username, string address, string city, string state, string postalCode)
        {
            var response = new ServiceResponse { Success = true };

            var userProfile = ProfileBase.Create(username, true) as UserProfile;

            userProfile.Address = address;
            userProfile.City = city;
            userProfile.State = state;
            userProfile.PostalCode = postalCode;

            try
            {
                userProfile.Save();
                response.Message = "Your profile was saved successfully.";
            }
            catch (Exception)
            {
                response.Success = false;
                response.Message = "Unable to save your profile at this time.";
            }            

            return response;
        }

        [WebInvoke]
        [OperationContract]
        public ServiceResponse GetSecurityQuestion(string username)
        {
            var response = new ServiceResponse { Success = false };

            MembershipUser user = System.Web.Security.Membership.GetUser(username);

            if (user != null)
            {
                response.Data = user.PasswordQuestion;
                response.Success = true;
            }
            else
            {
                response.Message = string.Format("User \"{0}\" does not exist.", username);
            }

            return response;
        }

        [WebInvoke]
        [OperationContract]
        public ServiceResponse SendResetPassword(string username, string securityAnswer)
        {
            var response = new ServiceResponse { Success = true };

            MembershipUser user = System.Web.Security.Membership.GetUser(username);

            if (user != null)
            {
                try
                {
                    user.ResetPassword(securityAnswer);
                    response.Success = true;
                }
                catch (Exception)
                {
                    response.Message = "We were unable to rest your password. Please try back at another time.";
                }
            }
            else
            {
                response.Message = string.Format("User \"{0}\" does not exist.", username);
            }

            return response;
        }
        
        [WebInvoke]
        [OperationContract]
        public ServiceResponse RegisterUser(MembershipData membershipData, UserProfileData profileData)
        {
            var response1 = CreateUser(membershipData.Username, membershipData.Password, 
                membershipData.EmailAddress, membershipData.securityQuestion, membershipData.securityAnswer);

            ServiceResponse response2 = null;
                
            if (response1.Success) 
            {
                response2 = SaveProfile(membershipData.Username, profileData.Address, profileData.City, 
                    profileData.State, profileData.PostalCode);
            }

            return new ServiceResponse 
                {  
                    Success = response1.Success || (response2 != null && response2.Success), 
                    Message = string.Format("{0} {1}", response1.Message, (response2 != null) ? response2.Message : "")
                };
        }
    }
}
